//
//  OAuthViewController.swift
//  WeiBoSwift
//
//  Created by 吴斌 on 2022/9/26.
//

import UIKit
import WebKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    // MARK: - 控件的属性
    @IBOutlet weak var webView: WKWebView!
    // 是否第一次加载
    var isFirstLoad : Bool = true
    
    // MARK: - 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.navigationDelegate = self

        // 1.设置导航栏的内容
        setupNavigationBar()
        
        // 2.加载网页
        loadPage()
    }
}

// MARK: - 设置UI界面相关
extension OAuthViewController {
    private func setupNavigationBar() {
        // 1.设置左侧的item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(closeItemClick))
        
        // 2.设置右侧的item
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(fillItemClick))
        
        // 3.设置标题
        title = "登录页面"
    }
    
    private func loadPage() {
        // 1.获取登录页面的URLString
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        
        // 2.创建对应的NSURL
        guard let url = NSURL(string: urlString) else {
            return
        }
        
        // 3.创建NSURLRequest对象
        let request = NSURLRequest(url: url as URL)
        
        // 4.加载request对象
        webView.load(request as URLRequest)
    }
}

// MARK: - 事件监听
extension OAuthViewController {
    
    @objc private func closeItemClick() {
        dismiss(animated: true, completion: nil)
    }
    @objc private func fillItemClick() {
        // 1.书写js代码 : javascript
        let jsCode = "document.getElementById('userId').value='18056416595';document.getElementById('passwd').value='Wubin180'"
        
        // 2.执行js代码
        webView.evaluateJavaScript(jsCode)
        
    }
    
}

// MARK: - webView的delegate
extension OAuthViewController : WKNavigationDelegate {
    // webView开始加载网页
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        SVProgressHUD.show()
    }
    
    // webView完成加载
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        SVProgressHUD.dismiss()
    }
    
    // webView加载失败
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    // 在发送请求之前，决定是否跳转 -> 默认允许
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        // 1.获取加载网页的NSURL
        guard let url = navigationAction.request.url else {
            decisionHandler(.allow)
            return
        }

        // 2.获取url中的字符串
        let urlString = url.absoluteString

        // 3.判断该字符串中是否包含code
        guard urlString.contains("code=") else {
            decisionHandler(.allow)
            return
        }

        // 4.将code截取出来
        let code = urlString.components(separatedBy: "code=").last!

        // 5.请求accessToken 这里会循环调用,应该是web循环加载导致的,我们做特殊处理
        if isFirstLoad {
            loadAccessToken(code: code)
        }
        
        decisionHandler(.cancel)
    }
    
    
}

// MARK: - 请求数据
extension OAuthViewController {
    // 请求AccessToken
    private func loadAccessToken(code: String) {
        NetworkTools.shareInstance.loadAccessToken(code: code) { result, error in
            // 1.错误校验
            if error != nil {
                print(error!)
                return
            }
            
            self.isFirstLoad = false
            
            // 2.拿到结果
            guard let accountDict = result else {
                print("没有获取到授权后的数据")
                return
            }
            
            // 3.将字典转模型
            let account = UserAccount(dict: accountDict)
            
            // 4.请求用户信息
            self.loadUserInfo(account: account)
            
        }
    }
    
    func loadUserInfo(account: UserAccount) {
        // 1.获取AccessToken
        guard let accessToken = account.access_token else { return }
        
        // 2.获取uid
        guard let uid = account.uid else { return }
        
        // 3.发送网络请求
        NetworkTools.shareInstance.loadUserInfo(access_token: accessToken, uid: uid) { result, error in
            // 1.错误校验
            if error != nil {
                print(error!)
                return
            }
            
            // 2.拿到用户信息的结果
            guard let userInfoDict = result else {
                return
            }
            
            // 3.从字典中取出昵称和用户头像地址
            account.screen_name = userInfoDict["screen_name"] as? String
            account.avatar_large = userInfoDict["avatar_large"] as? String
            
            // 4.将account对象保存
            NSKeyedArchiver.archiveRootObject(account, toFile: UserAccountViewModel.shareIntance.accountPath)
            
            // 5.将account对象设置到单例对象中
            UserAccountViewModel.shareIntance.account = account
            
            // 6.显示欢迎界面
            self.dismiss(animated: false) {
                UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController()
            }
        }
    }
}

